<!doctype html>



  


<html class="theme-next pisces use-motion" lang="zh-Hans">
<head><meta name="generator" content="Hexo 3.8.0">
  <meta name="baidu-site-verification" content="bk1wz1wzS4">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">



<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">












  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css">




  
  
  
  

  
    
    
  

  

  

  

  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Lato:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/css/main.css?v=5.1.0" rel="stylesheet" type="text/css">


  <meta name="keywords" content="学习,">








  <link rel="shortcut icon" type="image/x-icon" href="/favicon.ico?v=5.1.0">






<meta name="description" content="mongoose简介在说MongoDB数据插入操作之前，我们先来简单了解下它的数据逻辑结构。MongoDB的逻辑结构是一种层次结构，主要由：文档(document)、集合(collection)、数据库(database)这三部分组成的。文档(document)：由键/值对构成，像{a:1}；{s:”abc”}等，它是MongoDB核心单元，MongoDB的文档（document），相当于关系数据">
<meta name="keywords" content="学习">
<meta property="og:type" content="article">
<meta property="og:title" content="express之mongoose操作">
<meta property="og:url" content="https://youandme66.github.io/2017/03/12/third/index.html">
<meta property="og:site_name" content="腊月的季节">
<meta property="og:description" content="mongoose简介在说MongoDB数据插入操作之前，我们先来简单了解下它的数据逻辑结构。MongoDB的逻辑结构是一种层次结构，主要由：文档(document)、集合(collection)、数据库(database)这三部分组成的。文档(document)：由键/值对构成，像{a:1}；{s:”abc”}等，它是MongoDB核心单元，MongoDB的文档（document），相当于关系数据">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="https://youandme66.github.io/2017/03/12/third/mongoose1.png">
<meta property="og:updated_time" content="2017-03-12T09:29:58.000Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="express之mongoose操作">
<meta name="twitter:description" content="mongoose简介在说MongoDB数据插入操作之前，我们先来简单了解下它的数据逻辑结构。MongoDB的逻辑结构是一种层次结构，主要由：文档(document)、集合(collection)、数据库(database)这三部分组成的。文档(document)：由键/值对构成，像{a:1}；{s:”abc”}等，它是MongoDB核心单元，MongoDB的文档（document），相当于关系数据">
<meta name="twitter:image" content="https://youandme66.github.io/2017/03/12/third/mongoose1.png">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Pisces',
    sidebar: {"position":"left","display":"post"},
    fancybox: true,
    motion: true,
    duoshuo: {
      userId: '0',
      author: 'youandme'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://youandme66.github.io/2017/03/12/third/">





  <title> express之mongoose操作 | 腊月的季节 </title>
  <script>
  (function(){
    var bp = document.createElement('script');
    var curProtocol = window.location.protocol.split(':')[0];
    if (curProtocol === 'https') {
        bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';
    }
    else {
        bp.src = 'http://push.zhanzhang.baidu.com/push.js';
    }
    var s = document.getElementsByTagName("script")[0];
    s.parentNode.insertBefore(bp, s);
  })();
</script>
</head>

<body itemscope="" itemtype="http://schema.org/WebPage" lang="zh-Hans">

  










  
  
    
  

  <div class="container one-collumn sidebar-position-left page-post-detail ">
    <div class="headband"></div>

    <header id="header" class="header" itemscope="" itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-meta ">
  

  <div class="custom-logo-site-title">
    <a href="/" class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <span class="site-title">腊月的季节</span>
      <span class="logo-line-after"><i></i></span>
    </a>
  </div>
  <p class="site-subtitle"></p>
</div>

<div class="site-nav-toggle">
  <button>
    <span class="btn-bar"></span>
    <span class="btn-bar"></span>
    <span class="btn-bar"></span>
  </button>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br>
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br>
            
            关于
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br>
            
            标签
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br>
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup">
 <span class="search-icon fa fa-search"></span>
 <input type="text" id="local-search-input">
 <div id="local-search-result"></div>
 <span class="popup-btn-close">close</span>
</div>


    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal " itemscope="" itemtype="http://schema.org/Article">
  <link itemprop="mainEntityOfPage" href="https://youandme66.github.io/2017/03/12/third/">

  <span style="display:none" itemprop="author" itemscope="" itemtype="http://schema.org/Person">
    <meta itemprop="name" content="腊月的季节">
    <meta itemprop="description" content="">
    <meta itemprop="image" content="/uploads/avatar.jpg">
  </span>

  <span style="display:none" itemprop="publisher" itemscope="" itemtype="http://schema.org/Organization">
    <meta itemprop="name" content="腊月的季节">
    <span style="display:none" itemprop="logo" itemscope="" itemtype="http://schema.org/ImageObject">
      <img style="display:none;" itemprop="url image" alt="腊月的季节" src="">
    </span>
  </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">
            
            
              
                express之mongoose操作
              
            
          </h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>
              <time title="Post created" itemprop="dateCreated datePublished" datetime="2017-03-12T00:00:00+08:00">
                2017-03-12
              </time>
            

            

            
          </span>

          
            <span class="post-category">
              <span class="post-meta-divider">|</span>
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
              
                <span itemprop="about" itemscope="" itemtype="http://schema.org/Thing">
                  <a href="/categories/NodeJs/" itemprop="url" rel="index">
                    <span itemprop="name">NodeJs</span>
                  </a>
                </span>

                
                
                  ， 
                
              
                <span itemprop="about" itemscope="" itemtype="http://schema.org/Thing">
                  <a href="/categories/NodeJs/express/" itemprop="url" rel="index">
                    <span itemprop="name">express</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
            <!--noindex-->
              <span class="post-comments-count">
                <span class="post-meta-divider">|</span>
                <span class="post-meta-item-icon">
                  <i class="fa fa-comment-o"></i>
                  <a href="/2017/03/12/third/#comments" itemprop="discussionUrl">
                    <span class="post-comments-count hc-comment-count" data-xid="2017/03/12/third/" itemprop="commentsCount"></span>
                  </a>
                </span>
              </span>
              <!--/noindex-->
            
          

          

          
          
             <span id="/2017/03/12/third/" class="leancloud_visitors" data-flag-title="express之mongoose操作">
               <span class="post-meta-divider">|</span>
               <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>
               <span class="post-meta-item-text">阅读次数 </span>
               <span class="leancloud-visitors-count"></span>
              </span>
          

          

          

        </div>
      </header>
    


    <div class="post-body" itemprop="articleBody">

      
      

      
        <h3 id="mongoose简介"><a href="#mongoose简介" class="headerlink" title="mongoose简介"></a>mongoose简介</h3><p>在说MongoDB数据插入操作之前，我们先来简单了解下它的数据逻辑结构。<br>MongoDB的逻辑结构是一种层次结构，主要由：文档(document)、集合(collection)、数据库(database)这三部分组成的。<br>文档(document)：由键/值对构成，像{a:1}；{s:”abc”}等，它是MongoDB核心单元，MongoDB的文档（document），相当于关系数据库中的一行记录。<br>集合（Collection）：多个文档组成一个集合（collection），相当于关系数据库的表。<br>数据库（database）：多个集合（collection），逻辑上组织在一起，就是数据库（database）。<br>一个MongoDB实例支持多个数据库（database）。</p>
<h3 id="使用mongoose"><a href="#使用mongoose" class="headerlink" title="使用mongoose"></a>使用mongoose</h3><p>安装mongoose</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">npm install mongoose</span><br></pre></td></tr></table></figure>
<p>引用mongoose</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> mongoose = <span class="built_in">require</span>(<span class="string">"mongoose"</span>);</span><br></pre></td></tr></table></figure>
<p>使用mongoose链接数据库</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> db = mongoose(<span class="string">"mongodb://user:pass@localhost:port/database"</span>);</span><br></pre></td></tr></table></figure>
<p>示例:<br><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> mongoose = <span class="built_in">require</span>(“mongoose”); </span><br><span class="line"><span class="keyword">var</span> db = mongoose.connect(“mongodb:<span class="comment">//127.0.0.1:27017/test”); </span></span><br><span class="line">db.connection.on(“error”, <span class="function"><span class="keyword">function</span> (<span class="params">error</span>) </span>&#123; </span><br><span class="line"><span class="built_in">console</span>.log(“数据库连接失败：” + error); </span><br><span class="line">&#125;); </span><br><span class="line">db.connection.on(“open”, <span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123; </span><br><span class="line"><span class="built_in">console</span>.log(“——数据库连接成功！——”); </span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure></p>
<h3 id="mongodb基础"><a href="#mongodb基础" class="headerlink" title="mongodb基础"></a>mongodb基础</h3><p>Schema ： 一种以文件形式存储的数据库模型骨架，不具备数据库的操作能力<br>Model ： 由Schema发布生成的模型，具有抽象属性和行为的数据库操作对<br>Entity ： 由Model创建的实体，他的操作也会影响数据库<br>Schema —— 一种以文件形式存储的数据库模型骨架，无法直接通往数据库端，也就是说它不具备对数据库的操作能力，仅仅只是数据库模型在程序片段中的一种表现，可以说是数据属性模型(传统意义的表结构)，又或着是“集合”的模型骨架。<br>定义</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> mongoose = <span class="built_in">require</span>(<span class="string">"mongoose"</span>)</span><br><span class="line"><span class="keyword">var</span> TestSchema = <span class="keyword">new</span> mongoose.Schema(&#123;</span><br><span class="line">    name : &#123;<span class="attr">type</span>:<span class="built_in">String</span>&#125;,</span><br><span class="line">    age : &#123;<span class="attr">type</span>:<span class="built_in">Number</span>,<span class="attr">default</span>:<span class="number">0</span>&#125;,</span><br><span class="line">    time : &#123;<span class="attr">type</span>:<span class="built_in">Date</span>,<span class="attr">default</span>:<span class="built_in">Date</span>.now&#125;,</span><br><span class="line">    emial : &#123;<span class="attr">type</span>:<span class="built_in">String</span>,<span class="attr">default</span>:<span class="string">''</span>&#125;</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>
<p>基本属性类型有：字符串、日期型、数值型、布尔型(Boolean)、null、数组、内嵌文档等</p>
<p>Model —— 由Schema构造生成的模型，除了Schema定义的数据库骨架以外，还具有数据库操作的行为，类似于管理数据库属性、行为的类。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> db = mongoose.connect(<span class="string">"mongodb://127.0.0.1:27017/test"</span>);</span><br><span class="line"><span class="comment">// 通过Schema创建Model</span></span><br><span class="line"><span class="keyword">var</span> TestModel = db.model(<span class="string">"test1"</span>, TestSchema);</span><br></pre></td></tr></table></figure>
<p>数据库中的集合名称,当我们对其添加数据时如果test1已经存在，则会保存到其目录下，如果未存在，则会创建test1集合，然后在保存数据。</p>
<p>Entity —— 由Model创建的实体，使用save方法保存数据，Model和Entity都有能影响数据库的操作，但Model比Entity更具操作性。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> TestEntity = <span class="keyword">new</span> TestModel(&#123;</span><br><span class="line">    name : <span class="string">"Lenka"</span>,</span><br><span class="line">    age : <span class="number">36</span>,</span><br><span class="line">    email : <span class="string">"lenka@qq.com"</span></span><br><span class="line">&#125;);</span><br><span class="line"><span class="built_in">console</span>.log(TestEntity.name); <span class="comment">// Lenka</span></span><br><span class="line"><span class="built_in">console</span>.log(TestEntity.age); <span class="comment">// 36</span></span><br></pre></td></tr></table></figure>
<h3 id="mongoose-mongodb"><a href="#mongoose-mongodb" class="headerlink" title="mongoose-mongodb"></a>mongoose-mongodb</h3><p>1、定义模式(Schema)<br>每个模式映射mongoDB的一个集合（注意映射这个词，下面会讲为什么），它定义（只是定义，不是实现）这个集合里面文档的结构，就是定义这个文档有什么字段，字段类型是什么，字段默认值是什么等。除了定义结构外，还定义文档的实例方法，静态模型方法，复合索引，中间件等。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> mongoose = <span class="built_in">require</span>(<span class="string">'mongoose'</span>);</span><br><span class="line"><span class="keyword">var</span> Schema = mongoose.Schema;</span><br><span class="line"></span><br><span class="line"><span class="comment">/*定义模式Student_Schema*/</span></span><br><span class="line"><span class="keyword">var</span> Student_Schema = <span class="keyword">new</span> Schema(&#123;</span><br><span class="line">  name: <span class="built_in">String</span>,</span><br><span class="line">  id: <span class="built_in">Number</span>,</span><br><span class="line">  phone: <span class="built_in">String</span>,</span><br><span class="line">  date: <span class="built_in">Date</span></span><br><span class="line">&#125;, &#123;</span><br><span class="line">  versionKey: <span class="literal">false</span></span><br><span class="line">&#125;);</span><br><span class="line"></span><br><span class="line"><span class="comment">/*定义模型Student，注意数据库存的是students*/</span></span><br><span class="line">mongoose.model(<span class="string">"Student"</span>, Student_Schema);</span><br></pre></td></tr></table></figure>
<p>{versionKey: false}是干嘛用？如果不加这个设置，我们通过mongoose第一次创建某个集合时，它会给这个集合设定一个versionKey属性值，这个属性值包含这个文档的内部版本，数据库中显示为_v，如图：<br><img src="/2017/03/12/third/mongoose1.png" alt="图片加载中..."><br>通过{versionKey: false}可以配置这个参数，让数据库不再添加这个属性，格式是：new Schema({..}, { versionKey: false });<br>2、定义模型(Model)<br>模型用来实现我们定义的模式，调用mongoose.model来编译Schema得到Model。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/*定义模型Student，数据库存的是students*/</span></span><br><span class="line">mongoose.model(<span class="string">"Student"</span>, Student_Schema);</span><br></pre></td></tr></table></figure>
<p>为什么上面我强调模式的映射，那是因为模式仅仅是和db中集合文档的结构相对应（映射），它并不直接在数据库中操作这个结构，模型才是直接与数据库打交道的存在，可以这么说：模式是定义结构，模型是实现操作。当我们使用mongoose.model(“Student”, Student_Schema)创建Student模型对数据进行操作时，数据库会寻找一个名字叫students集合接受Student模型的操作，特别需要注意的是：1.如果是增加（instance.save）操作时，数据库中没有这个集合，数据库会自动创建这个集合存储数据，这个集合产生规则为：把Model名字字母全部变小写和在后面加复数s。2.如果是删改查三个操作数据库中没有这个集合，那就是没有，删除空修改空返回空。</p>
<p>3、访问模型</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> MyStudent = mongoose.model(<span class="string">"Student"</span>);</span><br></pre></td></tr></table></figure>
<p>到这里，已经基本完成了使用mongoose前提操作了。有没有觉得有点繁琐，其实我也觉得挺繁琐，幸运的是234可以一步创建：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> MyStudent = mongoose.model(<span class="string">'Student'</span>,&#123;</span><br><span class="line">  name: <span class="built_in">String</span>,</span><br><span class="line">  id: <span class="built_in">Number</span>,</span><br><span class="line">  phone: <span class="built_in">String</span>,</span><br><span class="line">  date: <span class="built_in">Date</span></span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>
<p>4、创建实例(instance)</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> sam = <span class="keyword">new</span> MyStudent(&#123;</span><br><span class="line">    name: <span class="string">"sam976"</span>,</span><br><span class="line">    id: <span class="number">123</span>,</span><br><span class="line">    phone: <span class="string">"18706888888"</span>,</span><br><span class="line">    date: <span class="built_in">Date</span>.now()</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>
<p>一般只在save（增加）操作中需要。</p>
<p>模型的实例是集合中真实的数据，就是collection中的document，用mysql中的术语来说就是一条记录。模型在数据库中建好了集合和文档结构后，通过实例往里面添加真实的document。<br>捋一捋模式、模型、实例的关系：模式定义了操作和属性，这些操作和属性包括mongoose自带和自定义，而模型和实例可以对模式里面定义的属性和方法进行引用。模型是mongoose用来和数据库直接打交道的中介，实例是往数据库存的真实数据。模式并非必须，那为什么要分开模式和模型呢？我觉得是遵循了软件设计中“定义和实现分开”这个原则。有的文章说模式没有操作数据库的能力，模型才有，对这个观点，我觉得部分对，虽说模式不能直接操作数据库，但模式定义的方法可以被模型用来操作数据库。官方文档是这么说的：</p>
<h3 id="model-find"><a href="#model-find" class="headerlink" title="model.find"></a>model.find</h3><p>Mongoose 模型提供了 find, findOne, 和 findById 方法用于文档查询。<br>Model.find(query, fields, options, callback)<br>// fields 和 options 都是可选参数<br>简单查询</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">Model.find(&#123; <span class="string">'csser.com'</span>: 5 &#125;, <span class="keyword">function</span> (err, docs) &#123; // docs 是查询的结果数组 &#125;);</span><br></pre></td></tr></table></figure>
<p>只查询指定键的结果</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">Model.find(&#123;&#125;, [<span class="string">'first'</span>, <span class="string">'last'</span>], <span class="keyword">function</span> (err, docs) &#123;</span><br><span class="line">  // docs 此时只包含文档的部分键值</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>
<h3 id="Model-findOne"><a href="#Model-findOne" class="headerlink" title="Model.findOne"></a>Model.findOne</h3><p>与 Model.find 相同，但只返回单个文档</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">Model.findOne(&#123; age: 5&#125;, <span class="keyword">function</span> (err, doc)&#123;</span><br><span class="line">  // doc 是单个文档</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>
<h3 id="Model-findById"><a href="#Model-findById" class="headerlink" title="Model.findById"></a>Model.findById</h3><p>与 findOne 相同，但它接收文档的 _id 作为参数，返回单个文档。_id 可以是字符串或 ObjectId 对象。</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">Model.findById(obj._id, <span class="keyword">function</span> (err, doc)&#123;</span><br><span class="line">  // doc 是单个文档</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>
<h3 id="Model-count"><a href="#Model-count" class="headerlink" title="Model.count"></a>Model.count</h3><p>返回符合条件的文档数</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">Model.count(conditions,callback)</span><br></pre></td></tr></table></figure>
<h3 id="Model-remove"><a href="#Model-remove" class="headerlink" title="Model.remove"></a>Model.remove</h3><p>删除符合的条件的文档</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">Model.remove(conditions,callback);</span><br></pre></td></tr></table></figure>
<h3 id="Model-distinct"><a href="#Model-distinct" class="headerlink" title="Model.distinct"></a>Model.distinct</h3><p>查询符合条件的文档并返回根据键分组的结果.<br>Model.distinct(field,conditions,callback);</p>
<h3 id="Model-where"><a href="#Model-where" class="headerlink" title="Model.where"></a>Model.where</h3><p>当查询比较复杂时，用where:</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">Model</span><br><span class="line">.<span class="built_in">where</span>(<span class="string">'age'</span>).gte(25)</span><br><span class="line">.<span class="built_in">where</span>(<span class="string">'tags'</span>).<span class="keyword">in</span>([<span class="string">'movie'</span>, <span class="string">'music'</span>, <span class="string">'art'</span>])</span><br><span class="line">.select(<span class="string">'name'</span>, <span class="string">'age'</span>, <span class="string">'tags'</span>)</span><br><span class="line">.skip(20)</span><br><span class="line">.<span class="built_in">limit</span>(10)</span><br><span class="line">.asc(<span class="string">'age'</span>)</span><br><span class="line">.slaveOk()</span><br><span class="line">.hint(&#123; age: 1, name: 1 &#125;)</span><br><span class="line">.run(callback);</span><br></pre></td></tr></table></figure>
<h3 id="Model-where-1"><a href="#Model-where-1" class="headerlink" title="Model.$where"></a>Model.$where</h3><p>有时我们需要在 mongodb 中使用 javascript 表达式进行查询，这时可以用 find({$where : javascript}) 方式，$where 是一种快捷方式，并支持链式调用查询。</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">Model.<span class="variable">$where</span>(<span class="string">'this.firstname === this.lastname'</span>).<span class="built_in">exec</span>(callback)</span><br></pre></td></tr></table></figure>
<h3 id="Model-update"><a href="#Model-update" class="headerlink" title="Model.update"></a>Model.update</h3><p>使用 update 子句更新符合指定条件的文档，更新数据在发送到数据库服务器之前会改变模型的类型。</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">var conditions = &#123; name: <span class="string">'borne'</span> &#125;</span><br><span class="line">  , update = &#123; <span class="variable">$inc</span>: &#123; visits: 1 &#125;&#125;</span><br><span class="line">  , options = &#123; multi: <span class="literal">true</span> &#125;;</span><br><span class="line"></span><br><span class="line">Model.update(conditions, update, options, callback)</span><br></pre></td></tr></table></figure>
<p>注意：为了向后兼容，所有顶级更新键如果不是原子操作命名的，会统一被按 $set 操作处理，例如：</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">var query = &#123; name: <span class="string">'borne'</span> &#125;;</span><br><span class="line">Model.update(query, &#123; name: <span class="string">'jason borne'</span> &#125;, options, callback)</span><br><span class="line"></span><br><span class="line">// 会被这样发送到数据库服务器</span><br><span class="line"></span><br><span class="line">Model.update(query, &#123; <span class="variable">$set</span>: &#123; name: <span class="string">'jason borne'</span> &#125;&#125;, options, callback)</span><br></pre></td></tr></table></figure>
<h3 id="查询API"><a href="#查询API" class="headerlink" title="查询API"></a>查询API</h3><p>如果不提供回调函数，所有这些方法都返回 Query 对象，它们都可以被再次修改（比如增加选项、键等），直到调用exec 方法。</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">var query = Model.find(&#123;&#125;);</span><br><span class="line"></span><br><span class="line">query.where(<span class="string">'field'</span>, 5);</span><br><span class="line">query.limit(5);</span><br><span class="line">query.skip(100);</span><br><span class="line">query.exec(<span class="keyword">function</span> (err, docs) &#123;</span><br><span class="line">  // called when the `query.complete` or `query.error` are called</span><br><span class="line">  // internally</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>
<h3 id="mongodb查询示例"><a href="#mongodb查询示例" class="headerlink" title="mongodb查询示例"></a>mongodb查询示例</h3><p>1、db.user.find({});<br>2、db.user.find();<br>3、db.user.find({“name”:”user2”});<br>4、db.user.find({},{“name”:1,”password”:1});<br>5、db.user.find({},{“_id”:0});<br>6、查询条件<br>\$lt,\$lte,\$gt,\$gte,\$ne和&lt;,&lt;=,&gt;,&gt;=,!=是一一对应的，它们可以组合起来以查找一个范围内的值。<br>db.user.find({“age”:{“\$gte”:”20”,”\$lte”:”30”}});<br>db.user.find({“age”:{“\$gte”:20,”\$lte”:30}});<br>7、关联查询<br>db.user.find({“age”:{“\$in”:[20,25,26]}});<br>db.user.find({“age”:{“\$nin”:[20,25,26]}});<br>db.user.find({“age”:{“\$in”:[20,25,26]}});<br>用$or用于对多个键做or查询。<br>db.user.find({“\$or”:[{“age”:{“in”:[24,25,26]}},{“name”:”user3”}]});<br>8、特定类型的查询<br>null查询<br>db.user.update({“name”:”user2”},{\$set:{“sex”:null}});<br>db.user.find({“sex”:{“\$in”:[null]}});<br>正则表达式<br>db.user.find({“name”:/^user/});<br>数组查询<br>db.food.find({fruit:{\$all:[“apple”,”banana”]}});<br>db.food.find({“fruit.2”:”peach”});<br>\$size:查询指定长度的数组<br>db.food.find({“fruit”:{“\$size”:3}});</p>

      
    </div>

    <div>
      
        

      
    </div>

    <div>
      
        

      
    </div>


    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/学习/" rel="tag"># 学习</a>
          
        </div>
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2017/03/11/second/" rel="next" title="angularjs之作用域详解">
                <i class="fa fa-chevron-left"></i> angularjs之作用域详解
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2017/03/12/second/" rel="prev" title="PCA算法步骤">
                PCA算法步骤 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </article>



    <div class="post-spread">
      
        <!-- JiaThis Button BEGIN -->
<div class="jiathis_style">
  <a class="jiathis_button_tsina"></a>
  <a class="jiathis_button_tqq"></a>
  <a class="jiathis_button_weixin"></a>
  <a class="jiathis_button_cqq"></a>
  <a class="jiathis_button_douban"></a>
  <a class="jiathis_button_renren"></a>
  <a class="jiathis_button_qzone"></a>
  <a class="jiathis_button_kaixin001"></a>
  <a class="jiathis_button_copy"></a>
  <a href="http://www.jiathis.com/share" class="jiathis jiathis_txt jiathis_separator jtico jtico_jiathis" target="_blank"></a>
  <a class="jiathis_counter_style"></a>
</div>
<script type="text/javascript">
  var jiathis_config={
    hideMore:false
  }
</script>
<script type="text/javascript" src="http://v3.jiathis.com/code/jia.js" charset="utf-8"></script>
<!-- JiaThis Button END -->

      
    </div>
  </div>


          </div>
          

  <p>热评文章</p>
  <div class="ds-top-threads" data-range="weekly" data-num-items="4"></div>


          
  <div class="comments" id="comments">
    
      <div id="hypercomments_widget"></div>
    
  </div>


        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope="" itemtype="http://schema.org/Person">
          <img class="site-author-image" itemprop="image" src="/uploads/avatar.jpg" alt="腊月的季节">
          <p class="site-author-name" itemprop="name">腊月的季节</p>
          <p class="site-description motion-element" itemprop="description">腊月的季节的个人博客</p>
        </div>
        <nav class="site-state motion-element">
          <div class="site-state-item site-state-posts">
            <a href="/archives">
              <span class="site-state-item-count">160</span>
              <span class="site-state-item-name">日志</span>
            </a>
          </div>

          
            <div class="site-state-item site-state-categories">
              <a href="/categories">
                <span class="site-state-item-count">72</span>
                <span class="site-state-item-name">分类</span>
              </a>
            </div>
          

          
            <div class="site-state-item site-state-tags">
              <a href="/tags">
                <span class="site-state-item-count">13</span>
                <span class="site-state-item-name">标签</span>
              </a>
            </div>
          

        </nav>

        

        <div class="links-of-author motion-element">
          
        </div>

        
        

        
        
          <div class="links-of-blogroll motion-element links-of-blogroll-inline">
            <div class="links-of-blogroll-title">
              <i class="fa  fa-fw fa-globe"></i>
              我的其他足迹
            </div>
            <ul class="links-of-blogroll-list">
              
                <li class="links-of-blogroll-item">
                  <a href="http://blog.csdn.net/qq_33433029" title="CSDN博客" target="_blank">CSDN博客</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="http://github.com/youandme66" title="GitHub" target="_blank">GitHub</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="http://www.jianshu.com/users/767025e0c4df/timeline" title="我的简书" target="_blank">我的简书</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="https://www.zhihu.com/people/liu-zhi-hao-85-39/activities" title="我的知乎" target="_blank">我的知乎</a>
                </li>
              
            </ul>
          </div>
        

        


      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-3"><a class="nav-link" href="#mongoose简介"><span class="nav-number">1.</span> <span class="nav-text">mongoose简介</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#使用mongoose"><span class="nav-number">2.</span> <span class="nav-text">使用mongoose</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#mongodb基础"><span class="nav-number">3.</span> <span class="nav-text">mongodb基础</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#mongoose-mongodb"><span class="nav-number">4.</span> <span class="nav-text">mongoose-mongodb</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#model-find"><span class="nav-number">5.</span> <span class="nav-text">model.find</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Model-findOne"><span class="nav-number">6.</span> <span class="nav-text">Model.findOne</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Model-findById"><span class="nav-number">7.</span> <span class="nav-text">Model.findById</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Model-count"><span class="nav-number">8.</span> <span class="nav-text">Model.count</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Model-remove"><span class="nav-number">9.</span> <span class="nav-text">Model.remove</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Model-distinct"><span class="nav-number">10.</span> <span class="nav-text">Model.distinct</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Model-where"><span class="nav-number">11.</span> <span class="nav-text">Model.where</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Model-where-1"><span class="nav-number">12.</span> <span class="nav-text">Model.$where</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Model-update"><span class="nav-number">13.</span> <span class="nav-text">Model.update</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#查询API"><span class="nav-number">14.</span> <span class="nav-text">查询API</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#mongodb查询示例"><span class="nav-number">15.</span> <span class="nav-text">mongodb查询示例</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">
  
  &copy;  2016 - 
  <span itemprop="copyrightYear">2019</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">腊月的季节</span>
</div>


<div class="powered-by">
   <a class="theme-link" href="http://www.jianshu.com/users/767025e0c4df/timeline">我的简书</a> 
</div>

<div class="theme-info">
  链接 -
  <a class="theme-link" href="https://www.zhihu.com/people/liu-zhi-hao-85-39/activities">
    我的知乎
  </a>
</div>


        

        
      </div>
    </footer>

    <div class="back-to-top">
      <i class="fa fa-arrow-up"></i>
    </div>
  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  



  
  <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>

  
  <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>

  
  <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.0"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.0"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.0"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.0"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.0"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.0"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.0"></script>


  



  




	

		<script type="text/javascript">
		_hcwp = window._hcwp || [];

		_hcwp.push({widget:"Bloggerstream", widget_id: 93245, selector:".hc-comment-count", label: "{\%COUNT%\}" });

		
		_hcwp.push({widget:"Stream", widget_id: 93245, xid: "2017/03/12/third/"});
		

		(function() {
		if("HC_LOAD_INIT" in window)return;
		HC_LOAD_INIT = true;
		var lang = (navigator.language || navigator.systemLanguage || navigator.userLanguage || "en").substr(0, 2).toLowerCase();
		var hcc = document.createElement("script"); hcc.type = "text/javascript"; hcc.async = true;
		hcc.src = ("https:" == document.location.protocol ? "https" : "http")+"://w.hypercomments.com/widget/hc/93245/"+lang+"/widget.js";
		var s = document.getElementsByTagName("script")[0];
		s.parentNode.insertBefore(hcc, s.nextSibling);
		})();
		</script>

	





  
  
  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length == 0) {
      search_path = "search.xml";
    }
    var path = "/" + search_path;
    // monitor main search box;

    function proceedsearch() {
      $("body").append('<div class="popoverlay">').css('overflow', 'hidden');
      $('.popup').toggle();
    }
    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';
      $.ajax({
        url: path,
        dataType: "xml",
        async: true,
        success: function( xmlResponse ) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = $( "entry", xmlResponse ).map(function() {
            return {
              title: $( "title", this ).text(),
              content: $("content",this).text(),
              url: $( "url" , this).text()
            };
          }).get();
          var $input = document.getElementById(search_id);
          var $resultContent = document.getElementById(content_id);
          $input.addEventListener('input', function(){
            var matchcounts = 0;
            var str='<ul class=\"search-result-list\">';
            var keywords = this.value.trim().toLowerCase().split(/[\s\-]+/);
            $resultContent.innerHTML = "";
            if (this.value.trim().length > 1) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var content_index = [];
                var data_title = data.title.trim().toLowerCase();
                var data_content = data.content.trim().replace(/<[^>]+>/g,"").toLowerCase();
                var data_url = decodeURIComponent(data.url);
                var index_title = -1;
                var index_content = -1;
                var first_occur = -1;
                // only match artiles with not empty titles and contents
                if(data_title != '') {
                  keywords.forEach(function(keyword, i) {
                    index_title = data_title.indexOf(keyword);
                    index_content = data_content.indexOf(keyword);
                    if( index_title >= 0 || index_content >= 0 ){
                      isMatch = true;
                      if (i == 0) {
                        first_occur = index_content;
                      }
                    }

                  });
                }
                // show search results
                if (isMatch) {
                  matchcounts += 1;
                  str += "<li><a href='"+ data_url +"' class='search-result-title'>"+ data_title +"</a>";
                  var content = data.content.trim().replace(/<[^>]+>/g,"");
                  if (first_occur >= 0) {
                    // cut out 100 characters
                    var start = first_occur - 20;
                    var end = first_occur + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if(start == 0){
                      end = 50;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    var match_content = content.substring(start, end);
                    // highlight all keywords
                    keywords.forEach(function(keyword){
                      var regS = new RegExp(keyword, "gi");
                      match_content = match_content.replace(regS, "<b class=\"search-keyword\">"+keyword+"</b>");
                    });

                    str += "<p class=\"search-result\">" + match_content +"...</p>"
                  }
                  str += "</li>";
                }
              })};
            str += "</ul>";
            if (matchcounts == 0) { str = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>' }
            if (keywords == "") { str = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>' }
            $resultContent.innerHTML = str;
          });
          proceedsearch();
        }
      });}

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched == false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(function(e){
      $('.popup').hide();
      $(".popoverlay").remove();
      $('body').css('overflow', '');
    });
    $('.popup').click(function(e){
      e.stopPropagation();
    });
  </script>


  
  
    <script type="text/x-mathjax-config">
      MathJax.Hub.Config({
        tex2jax: {
          inlineMath: [ ['$','$'], ["\\(","\\)"]  ],
          processEscapes: true,
          skipTags: ['script', 'noscript', 'style', 'textarea', 'pre', 'code']
        }
      });
    </script>

    <script type="text/x-mathjax-config">
      MathJax.Hub.Queue(function() {
        var all = MathJax.Hub.getAllJax(), i;
        for (i=0; i < all.length; i += 1) {
          all[i].SourceElement().parentNode.className += ' has-jax';
        }
      });
    </script>
    <script type="text/javascript" src="//cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>
  


  

  
  <script src="https://cdn1.lncld.net/static/js/av-core-mini-0.6.1.js"></script>
  <script>AV.initialize("EAvSG3QtXW1dqzq5WQ5CjH7S-gzGzoHsz", "2aiWv7vIfVY4CjKc49aPBHFX");</script>
  <script>
    function showTime(Counter) {
      var query = new AV.Query(Counter);
      var entries = [];
      var $visitors = $(".leancloud_visitors");

      $visitors.each(function () {
        entries.push( $(this).attr("id").trim() );
      });

      query.containedIn('url', entries);
      query.find()
        .done(function (results) {
          var COUNT_CONTAINER_REF = '.leancloud-visitors-count';

          if (results.length === 0) {
            $visitors.find(COUNT_CONTAINER_REF).text(0);
            return;
          }

          for (var i = 0; i < results.length; i++) {
            var item = results[i];
            var url = item.get('url');
            var time = item.get('time');
            var element = document.getElementById(url);

            $(element).find(COUNT_CONTAINER_REF).text(time);
          }
          for(var i = 0; i < entries.length; i++) {
            var url = entries[i];
            var element = document.getElementById(url);
            var countSpan = $(element).find(COUNT_CONTAINER_REF);
            if( countSpan.text() == '') {
              countSpan.text(0);
            }
          }
        })
        .fail(function (object, error) {
          console.log("Error: " + error.code + " " + error.message);
        });
    }

    function addCount(Counter) {
      var $visitors = $(".leancloud_visitors");
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();
      var query = new AV.Query(Counter);

      query.equalTo("url", url);
      query.find({
        success: function(results) {
          if (results.length > 0) {
            var counter = results[0];
            counter.fetchWhenSave(true);
            counter.increment("time");
            counter.save(null, {
              success: function(counter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(counter.get('time'));
              },
              error: function(counter, error) {
                console.log('Failed to save Visitor num, with error message: ' + error.message);
              }
            });
          } else {
            var newcounter = new Counter();
            /* Set ACL */
            var acl = new AV.ACL();
            acl.setPublicReadAccess(true);
            acl.setPublicWriteAccess(true);
            newcounter.setACL(acl);
            /* End Set ACL */
            newcounter.set("title", title);
            newcounter.set("url", url);
            newcounter.set("time", 1);
            newcounter.save(null, {
              success: function(newcounter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(newcounter.get('time'));
              },
              error: function(newcounter, error) {
                console.log('Failed to create');
              }
            });
          }
        },
        error: function(error) {
          console.log('Error:' + error.code + " " + error.message);
        }
      });
    }

    $(function() {
      var Counter = AV.Object.extend("Counter");
      if ($('.leancloud_visitors').length == 1) {
        addCount(Counter);
      } else if ($('.post-title-link').length > 1) {
        showTime(Counter);
      }
    });
  </script>



  
<script>
(function(){
    var bp = document.createElement('script');
    var curProtocol = window.location.protocol.split(':')[0];
    if (curProtocol === 'https') {
        bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';        
    }
    else {
        bp.src = 'http://push.zhanzhang.baidu.com/push.js';
    }
    var s = document.getElementsByTagName("script")[0];
    s.parentNode.insertBefore(bp, s);
})();
</script>


  

</body>
</html>
